#include "sequencerunframe.h"
#include "ui_sequencerunframe.h"
#include "sourcemanage.h"
#include "widgetmanage.h"

#include "mainframe.h"
#include "expframe.h"

SequenceRunFrame::SequenceRunFrame(QWidget *parent,Experiment* pExperiment) :
    QFrame(parent),
    ui(new Ui::SequenceRunFrame)
{
    ui->setupUi(this);
    this->pExperiment=pExperiment;

    pNetDealwith=SM->GetNetDealwith();
    connect(pNetDealwith,SIGNAL(SIG_StateChanged(QString)),this,SLOT(OnStateChanged(QString)));
    connect(pNetDealwith,SIGNAL(SIG_WorkFlowFinished(int)),this,SLOT(OnWorkFlowFinished(int)));
    connect(pNetDealwith,SIGNAL(SIG_ExpStateChanged(QString)),this,SLOT(OnExpStateChanged(QString)));
    connect(pNetDealwith,SIGNAL(SIG_ResponseTimeout(uchar,uchar)),this,SLOT(OnResponseTimeout(uchar,uchar)));
    connect(pNetDealwith,SIGNAL(SIG_WaitIn(int)),this,SLOT(OnWaitIn(int)));
    connect(pNetDealwith,SIGNAL(SIG_ExpFinish(int)),this,SLOT(OnExpFinish(int)));
    connect(pNetDealwith,SIGNAL(SIG_ExpScanChanged(QString,int,int,int)),
            this,SLOT(OnExpScanChanged(QString,int,int,int)));
     connect(pNetDealwith,SIGNAL(SIG_ReadResult(QList<ExpRawData>)),
             this,SLOT(UpdateResult(QList<ExpRawData>)));

    ui->treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);//ActionsContextMenu:不能分组
    connect(ui->treeWidget,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(OnCustomContextMenuRequested(QPoint)));
    pMenu = new QMenu(this);

    LoadData();

    UpdateExpButton(0);
    OnWorkFlowFinished(0);
}

SequenceRunFrame::~SequenceRunFrame()
{
    delete ui;
}

void SequenceRunFrame::LoadData()
{
    ui->treeWidget->clear();
    QTreeWidgetItem *pItem0=new QTreeWidgetItem(ui->treeWidget);
    pItem0->setIcon(0,QIcon(":/images/queuefinished.png"));
    pItem0->setText(0,"已完成序列");
    ui->treeWidget->addTopLevelItem(pItem0);
    pItem1=new QTreeWidgetItem(ui->treeWidget);
    pItem1->setIcon(0,QIcon(":/images/queuenotstart.png"));
    pItem1->setText(0,"未完成序列");
    ui->treeWidget->addTopLevelItem(pItem1);

    QueueExp *pQueueExp=SM->GetQueueExp();
    QStringList lists=pQueueExp->GetFilePaths();
    for(int index=0;index<lists.count();index++)
    {
        QString filePath=lists.at(index);
        Experiment exp=pQueueExp->GetExp(filePath);

        QFileInfo fileInfor(filePath);
        QTreeWidgetItem *pItemExp=new QTreeWidgetItem(QStringList()<<fileInfor.fileName()<<fileInfor.filePath());

        if(exp.IsFinished()==2)
        {
            pItem0->addChild(pItemExp);
            SetExpScanState(pItemExp,1);
        }
        else
        {
            pItem1->addChild(pItemExp);
            SetExpScanState(pItemExp,0);
        }

        pExpSample=exp.GetExpSamplePtr();
        QList<SampleInfor> sampleInfors=pExpSample->GetSampleInfors();
        for(int i=0;i<sampleInfors.count();i++)
        {
            SampleInfor sampleInfor=sampleInfors.at(i);
            QTreeWidgetItem *pItemSample=new QTreeWidgetItem(pItemExp);
            pItemSample->setText(0,sampleInfor.sampleName);
            SetSampleScanState(pItemSample,sampleInfor.scanState);
            for(int j=0;j<sampleInfor.preScanCount;j++)
            {
                QString name=QString("预扫描%1").arg(j+1);
                QTreeWidgetItem *pItemScan=new QTreeWidgetItem(pItemSample);
                pItemScan->setText(0,name);
                PreScanResult* pScanResult=sampleInfor.GetPreScanResultPtr(j);
                SetPreScanState(pItemScan,pScanResult->scanState.state);//
            }
            for(int j=0;j<sampleInfor.mainScanCount;j++)
            {
                QString name=QString("主扫描%1").arg(j+1);
                QTreeWidgetItem *pItemScan=new QTreeWidgetItem(pItemSample);
                pItemScan->setText(0,name);
                MainScanResult* pScanResult=sampleInfor.GetMainScanResultPtr(j);
                SetMainScanState(pItemScan,pScanResult->GetMainScanState());//
            }
        }
    }
}

//menu
void SequenceRunFrame::OnCustomContextMenuRequested(const QPoint &pos)
{
    QTreeWidgetItem *pItem=ui->treeWidget->itemAt(pos);
    //qDebug()<<"pItem"<<pItem;
    if(pItem==NULL) return;//

    QString text=pItem->text(0);
    pMenu->clear();
    if(text=="已完成序列"||text=="未完成序列")
    {
        pMenu->addAction(ui->actionDelAll);
    }
    else if(text.contains(".exp"))
    {
       pMenu->addAction(ui->actionDel);
       pMenu->addAction(ui->actionOpen);
    }
    pMenu->exec(QCursor::pos());//在当前鼠标位置显示
}

void SequenceRunFrame::on_actionDel_triggered()
{
    if(expRunState==1)
    {
        QMessageBox::information(this,tr("提示"),tr("序列运行中，无法删除！"));
        return;
    }

    QTreeWidgetItem *pItem=ui->treeWidget->currentItem();
    QueueExp *queueExp=SM->GetQueueExp();
    QString text=pItem->text(1);//两列 第二列记录文件名
    bool state=queueExp->RemoveExp(text);
    qDebug()<<"del state"<<state;

    LoadData();
}

void SequenceRunFrame::on_actionDelAll_triggered()
{
    if(expRunState==1)
    {
        QMessageBox::information(this,tr("提示"),tr("序列运行中，无法删除！"));
        return;
    }
    QTreeWidgetItem *pItem=ui->treeWidget->currentItem();
    QList<QTreeWidgetItem *> items=pItem->takeChildren();
    foreach(QTreeWidgetItem *item,items)
    {
        QueueExp *queueExp=SM->GetQueueExp();
        QString text=item->text(1);
        bool state=queueExp->RemoveExp(text);
        qDebug()<<"del state"<<state;
    }

    LoadData();
}

void SequenceRunFrame::on_actionOpen_triggered()
{
    QTreeWidgetItem *pItem=ui->treeWidget->currentItem();
    QString filePath=pItem->text(1);//两列 第二列记录文件名
    QFileInfo fileInfo(filePath);
    QString name=QString("实验[%1]").arg(fileInfo.fileName());
    MainFrame *pMainFrame=(MainFrame*)WM->GetWidget("MainFrame");
    if(pMainFrame->IsOpened(name)==true) return;//

    Experiment *pExperiment=new Experiment;
    QueueExp *queueExp=SM->GetQueueExp();
    *pExperiment=queueExp->GetExp(filePath);//
    //FM->LoadFromFile(filePath,pExperiment);
    ExpFrame *pWidget=new ExpFrame(this,pExperiment);
    pExperiment->SetFilePath(filePath);

    pMainFrame->AddTab(pWidget,name);
    connect(pWidget,SIGNAL(SIG_ExpSave(QString)),pMainFrame,SLOT(UpdateExpName(QString)));
}

//实验动作
void SequenceRunFrame::on_toolButton_Update_clicked()
{
    LoadData();
}

void SequenceRunFrame::on_toolButton_Start_clicked()
{
    //检测是否有未完成实验
    pNetDealwith->StartExp();
    UpdateExpButton(1);
    //pNetDealwith->ReadSerialNum();
    //pNetDealwith->ReadSoftwareVersion(1);
}

void SequenceRunFrame::on_toolButton_Stop_clicked()
{
    pNetDealwith->OnStop();
    UpdateExpButton(0);
}

void SequenceRunFrame::on_toolButton_SkipSample_clicked()
{

}

void SequenceRunFrame::on_toolButton_SkipExp_clicked()
{

}

//Exp Sequence
void SequenceRunFrame::SetExpScanState(QTreeWidgetItem *pItem,int state)
{
    switch(state)
    {
    case 0:
        pItem->setIcon(0,QIcon(":/images/queueexperimentnotfinished.gif"));
        break;
    case 1:
        pItem->setIcon(0,QIcon(":/images/queueexperimentfinished.gif"));
        break;
    case 2:

        break;
    }
}
void SequenceRunFrame::SetSampleScanState(QTreeWidgetItem *pItem,int state)
{
    switch(state)
    {
    case 0:
        pItem->setIcon(0,QIcon(":/images/queuesamplefinished.png"));//queuesamplenotstart
        break;
    case 1:
        pItem->setIcon(0,QIcon(":/images/queuesamplerunning.png"));
        break;
    case 2:
        pItem->setIcon(0,QIcon(":/images/queuesamplenotstart.png"));//
        break;
    default://
        pItem->setIcon(0,QIcon(":/images/queuesamplefinished.png"));
        break;
    }
}
void SequenceRunFrame::SetPreScanState(QTreeWidgetItem *pItem,int state)
{
    switch(state)
    {
    case 0:
        pItem->setIcon(0,QIcon(":/images/queuescannotstart.png"));
        break;
    case 1:
        pItem->setIcon(0,QIcon(":/images/queuescanrunning.png"));
        break;
    case 2:
        pItem->setIcon(0,QIcon(":/images/queuescanfinished.png"));
        break;
    }
}
void SequenceRunFrame::SetMainScanState(QTreeWidgetItem *pItem,int state)
{
    switch(state)
    {
    case 0:
        pItem->setIcon(0,QIcon(":/images/queuescannotstart.png"));
        break;
    case 1:
        pItem->setIcon(0,QIcon(":/images/queuescanrunning.png"));
        break;
    case 2:
        pItem->setIcon(0,QIcon(":/images/queuescanfinished.png"));
        break;
    }
}
void SequenceRunFrame::OnExpScanChanged(QString path,int sampleIndex,int preIndex,int mainIndex)
{
    //qDebug()<<"path"<<path<<sampleIndex<<preIndex<<mainIndex;
    Experiment exp=SM->GetQueueExp()->GetExp(path);
    pExpSample=exp.GetExpSamplePtr();
    QList<SampleInfor> sampleInfors=pExpSample->GetSampleInfors();
    SampleInfor sampleInfor=sampleInfors.at(sampleIndex);

    for(int i=0;i<pItem1->childCount();i++)
    {
        QTreeWidgetItem *pItem=pItem1->child(i);
        if(pItem->text(1)==path)
        {
            QTreeWidgetItem *pItemSample=pItem->child(sampleIndex);
            SetSampleScanState(pItemSample,sampleInfor.scanState);

            for(int j=0;j<sampleInfor.preScanCount;j++)
            {
                QTreeWidgetItem *pItemScan=pItemSample->child(j);
                PreScanResult* pScanResult=sampleInfor.GetPreScanResultPtr(j);
                SetPreScanState(pItemScan,pScanResult->scanState.state);//
            }
            for(int j=0;j<sampleInfor.mainScanCount;j++)
            {
                QTreeWidgetItem *pItemScan=pItemSample->child(sampleInfor.preScanCount+j);
                MainScanResult* pScanResult=sampleInfor.GetMainScanResultPtr(j);
                SetMainScanState(pItemScan,pScanResult->GetMainScanState());//
            }
        }
    }
    //如实验打开，同步实验显示
    //save
}
void SequenceRunFrame::OnExpFinish(int state)
{
    LoadData();
    UpdateExpButton(0);

    //如实验打开，同步实验显示
}
void SequenceRunFrame::UpdateResult(QList<ExpRawData>)
{
    //如实验打开，同步实验显示
}

// update
void SequenceRunFrame::OnExpStateChanged(QString text)
{
    ui->listWidget->addItem(text);
}

void SequenceRunFrame::OnResponseTimeout(uchar cmd1,uchar cmd2)
{
    QMessageBox::information(this,tr("提示"),tr("主命令%1辅命令%2超时！").arg(cmd1).arg(cmd2));
}
void SequenceRunFrame::OnWaitIn(int type)
{
    QString info;
    if(type==1)
    {
        info="装置放入样品中？";
    }
    else if(type==2)
    {
        info="装置放入清洗液中？";
    }
    QMessageBox::StandardButton button=QMessageBox::question(this,tr("询问"),info,QMessageBox::YesToAll | QMessageBox::Yes
                                                             | QMessageBox::No);

    if(button==QMessageBox::YesToAll)
    {
        pNetDealwith->SetWaitIn(2);
    }
    else if(button==QMessageBox::Yes)
    {
        pNetDealwith->SetWaitIn(1);
    }
    else //
    {
        pNetDealwith->SetWaitIn(0);
    }
}

void SequenceRunFrame::UpdateExpButton(int state)
{
    expRunState=state;
    if(state==0)//
    {
        ui->toolButton_Start->setEnabled(true);
        ui->toolButton_Stop->setEnabled(false);
        ui->toolButton_SkipExp->setEnabled(false);
        ui->toolButton_SkipSample->setEnabled(false);
    }
    else if(state==1)//running
    {
        ui->toolButton_Start->setEnabled(false);
        ui->toolButton_Stop->setEnabled(true);
        ui->toolButton_SkipExp->setEnabled(true);
        ui->toolButton_SkipSample->setEnabled(true);
    }
}

//工作流程
void SequenceRunFrame::on_pushButton_OpenVacuum_clicked()
{
    bool state=pNetDealwith->ProcessWorkFlow("打开真空");
    if(state==false) return;
    UpdateButton(1);
}

void SequenceRunFrame::on_pushButton_CloseVacuum_clicked()
{
    bool state=pNetDealwith->ProcessWorkFlow("关闭真空");
    if(state==false) return;
    UpdateButton(2);
}

void SequenceRunFrame::on_pushButton_OpenPlasma_clicked()
{
    bool state=pNetDealwith->ProcessWorkFlow("打开等离子体");
    if(state==false) return;
    UpdateButton(3);
}

void SequenceRunFrame::on_pushButton_ClosePlasma_clicked()
{
    QMessageBox::StandardButton button=QMessageBox::question(this,tr("询问"),tr("确定关闭等离子体？"));
    if(button==QMessageBox::Yes)
    {
        bool state=pNetDealwith->ProcessWorkFlow("关闭等离子体");
        if(state==false) return;
        UpdateButton(4);
    }
    else if(button==QMessageBox::No)
    {

    }
    else if(button==QMessageBox::Cancel||QMessageBox::Close)
    {

    }
}


//flow state update
void SequenceRunFrame::OnStateChanged(QString text)
{
    ui->lineEdit->setText(text);
}
void SequenceRunFrame::OnWorkFlowFinished(int flag)
{
    SystemState state=SM->GetSystemState();
    switch(state.READY)
    {
        case 0:
            ui->pushButton_OpenVacuum->setEnabled(true);
            ui->pushButton_CloseVacuum->setEnabled(false);
            ui->pushButton_OpenPlasma->setEnabled(false);
            ui->pushButton_ClosePlasma->setEnabled(false);//关闭等离子体
            break;
        case 1:
            ui->pushButton_OpenVacuum->setEnabled(false);
            ui->pushButton_CloseVacuum->setEnabled(true);
            ui->pushButton_OpenPlasma->setEnabled(true);
            ui->pushButton_ClosePlasma->setEnabled(false);//关闭等离子体
            break;
        case 2:
            ui->pushButton_OpenVacuum->setEnabled(false);
            ui->pushButton_CloseVacuum->setEnabled(false);
            ui->pushButton_OpenPlasma->setEnabled(false);
            ui->pushButton_ClosePlasma->setEnabled(true);//关闭等离子体
            break;
    }
}
void SequenceRunFrame::UpdateButton(int state)//流程工作中，禁止手动调节参数
{
    switch(state)
    {
        case 1:
            ui->pushButton_OpenVacuum->setEnabled(false);
            ui->pushButton_CloseVacuum->setEnabled(true);
            ui->pushButton_OpenPlasma->setEnabled(false);
            ui->pushButton_ClosePlasma->setEnabled(false);
            break;
        case 2:
            ui->pushButton_OpenVacuum->setEnabled(false);
            ui->pushButton_CloseVacuum->setEnabled(false);
            ui->pushButton_OpenPlasma->setEnabled(false);
            ui->pushButton_ClosePlasma->setEnabled(false);
            break;
        case 3:
            ui->pushButton_OpenVacuum->setEnabled(false);
            ui->pushButton_CloseVacuum->setEnabled(false);
            ui->pushButton_OpenPlasma->setEnabled(false);
            ui->pushButton_ClosePlasma->setEnabled(true);//异常退出
            break;
        case 4:
            ui->pushButton_OpenVacuum->setEnabled(false);
            ui->pushButton_CloseVacuum->setEnabled(false);
            ui->pushButton_OpenPlasma->setEnabled(false);
            ui->pushButton_ClosePlasma->setEnabled(false);
            break;
    }
}


